<route lang="json5" type="page">
  {
    layout: 'default',
    style: {
      navigationBarTitleText: '优惠券',
    },
    anonymous: false
  }
</route>

<script lang="ts" setup>
import CouponItem from './components/CouponItem.vue'
import { CouponPageType } from '@/enum'
import { ShopApi } from '@/apis'
// import { getCouponList } from '@/apis/course'
import { ofDate } from '@/utils/common'

const pType = ref<CouponPageType>(CouponPageType.view)

const couponOptions = ref<{
  disabled: boolean
  select: boolean
  coupon: ShopApi.CouponDetail
}[]>([])

function isExpired(startValidTime: string, endValidTime: string) {
  const startTime = ofDate(startValidTime)
  const endTime = ofDate(endValidTime)
  const now = new Date()
  return now < startTime || now > endTime
}

const getCouponList = async () => {
  const res = await ShopApi.getCouponList({ couponStatus: 1 })
  couponOptions.value = res.map(item => ({
    disabled: isExpired(item.startValidTime, item.endValidTime),
    select: false,
    coupon: item,
  }))
}

const selectHandle = (item) => {
  if (pType.value == CouponPageType.select) {
    item.select = !item.select
  }
}

const confirm = () => {
  const selectedList = couponOptions.value.filter(item => item.select)
  if (selectedList.length) {
    uni.setStorageSync('couponList', JSON.stringify(selectedList.map(item => item.coupon.id)))
    uni.navigateBack()
  } else {
    uni.showToast({
      title: '请选择优惠券',
      icon: 'none',
    })
  }
}

onLoad((options: { type: CouponPageType }) => {
  console.log(options)
  pType.value = options.type || CouponPageType.view
})

const { loading, data } = useRequest(getCouponList)
</script>

<template>
  <view v-if="loading" class="flex-row-center-center bg-white page">
    <wd-loading color="#33AD7C" />
  </view>
  <template v-else>
    <view class="content px py">
      <view v-if="!couponOptions.length">
        <wd-status-tip image="content" tip="暂无优惠券可用" />
      </view>
      <view v-for="(item, index) in couponOptions" :key="index" class="mb-[24rpx]">
        <CouponItem :disabled="item.disabled" :active="item.select" :coupon="item.coupon" @click="selectHandle(item)" />
      </view>
    </view>

    <view v-if="pType == CouponPageType.select" class="footer">
      <view class="px-[30rpx] py-[12rpx]">
        <wd-button block type="success" :round="false" @click="confirm">
          确定
        </wd-button>
      </view>
    </view>
  </template>
</template>

<style lang="scss" scoped>
  .content {
    height: calc(100vh - 160rpx) !important;
    overflow: scroll;
  }

  .footer {
    position: fixed;
    left: 0px;
    bottom: 0px;

    height: 160rpx;
    width: 100%;
    background: white;
    box-shadow: 0px -4px 4px 0px #0000000D;

  }
</style>
